package com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.fullapply

import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.bumptech.glide.Glide
import com.helasasa.maxfunds.lineofcredit.cashloan.R
import com.helasasa.maxfunds.lineofcredit.cashloan.databinding.ActivityGhanaFullApplyBinding
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.hitPoint
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.facedoing.FaceGhanaDoingActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.facedoing.REQUEST_CODE_ACTIVITY_FACE_DOING
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.idcarddoing.IdcardGhanaDoingActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.idcarddoing.REQUEST_CODE_ACTIVITY_IDCARD_DOING
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.picturedoing.PictureGhanaDoingActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.picturedoing.REQUEST_CODE_ACTIVITY_PICTURE_DOING
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.proof.subview.IProofGhanaPhotoPickerListener
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.proof.subview.ProofGhanaPhotoPicker
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.subview.HotlineGhanaDialog
import com.vmadalin.easypermissions.EasyPermissions
import com.vmadalin.easypermissions.dialogs.DEFAULT_SETTINGS_REQ_CODE
import com.vmadalin.easypermissions.dialogs.SettingsDialog

class FullApplyGhanaActivity : AppCompatActivity(), EasyPermissions.PermissionCallbacks,
    EasyPermissions.RationaleCallbacks {

    private lateinit var fullApplyViewModel: FullApplyGhanaViewModel
    private lateinit var binding: ActivityGhanaFullApplyBinding
    private lateinit var imagePicker: ProofGhanaPhotoPicker
    private lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 数据模型
        fullApplyViewModel = ViewModelProvider(this)[FullApplyGhanaViewModel::class.java]

        // 关联布局
        binding = ActivityGhanaFullApplyBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 用到的控件
        val hotline = binding.navbarRight
        val back = binding.navbarLeft
        val idcardFront = binding.idcardFront
        val idcardBack = binding.idcardBack
        val startFace = binding.startFace
        val payroll = binding.payroll
        val waterBills = binding.waterBills
        val phoneBills = binding.phoneBills
        val loading = binding.loading

        imagePicker = ProofGhanaPhotoPicker(object : IProofGhanaPhotoPickerListener {
            override fun onClick(type: Int) {
                if (0 == type) {
                    // take picture
                    val gTagInt = fullApplyViewModel.pickPicIndex
                    if ((0 == gTagInt) or (1 == gTagInt)) {
                        val intent = Intent(
                            this@FullApplyGhanaActivity,
                            IdcardGhanaDoingActivity::class.java
                        )
                        intent.putExtra("imageOutputTag", gTagInt.toString())
                        startActivityForResult(intent, REQUEST_CODE_ACTIVITY_IDCARD_DOING)
                    } else {
                        val intent = Intent(
                            this@FullApplyGhanaActivity,
                            PictureGhanaDoingActivity::class.java
                        )
                        intent.putExtra("imageOutputTag", gTagInt.toString())
                        startActivityForResult(intent, REQUEST_CODE_ACTIVITY_PICTURE_DOING)
                    }
                } else {
                    // ablum
                    pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
                }
            }
        })

        // 页面loading状态接口监听
        fullApplyViewModel.loadingResult.observe(this@FullApplyGhanaActivity, Observer {
            val loadingResult = it ?: return@Observer

            if (loadingResult) {
                loading.visibility = View.VISIBLE
            } else {
                loading.visibility = View.GONE
            }
        })

        // 页面UI状态接口监听
        fullApplyViewModel.pageDetailResult.observe(this@FullApplyGhanaActivity, Observer {
            val pageDetailResult = it ?: return@Observer

            if (pageDetailResult.error != null) {
                showMessage(pageDetailResult.error)
            }

            selectType(pageDetailResult)
        })

        // 保存ocr接口监听
        fullApplyViewModel.saveOcrResult.observe(this@FullApplyGhanaActivity, Observer {
            val saveOcrResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (saveOcrResult.error != null) {
                showMessage(saveOcrResult.error)
            }
        })

        // 流程接口监听
        fullApplyViewModel.mainProcessResult.observe(this@FullApplyGhanaActivity, Observer {
            val mainProcessResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (mainProcessResult.error != null) {
                showMessage(mainProcessResult.error)
            }

            if (mainProcessResult.success != null) {
                fullApplyViewModel.nextRouter(mainProcessResult.success)
            }
        })

        // 页面需要跳转监听
        fullApplyViewModel.nextRouterResult.observe(this@FullApplyGhanaActivity, Observer {
            val nextRouterResult = it ?: return@Observer

            loading.visibility = View.GONE
            startNextActivity(nextRouterResult.nextPage)
        })

        // 跳转相册监听
        pickMedia =
            registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
                if (uri != null) {
                    val gTagInt = fullApplyViewModel.pickPicIndex
                    fullApplyViewModel.handlePickImageResult(
                        this@FullApplyGhanaActivity,
                        uri,
                        gTagInt
                    )
                } else {
                    Log.d("PhotoPicker", "No media selected")
                }
            }

        // 点击客服
        hotline.setOnClickListener {
            // 客服弹框
            HotlineGhanaDialog().showNow(supportFragmentManager, "hotline")
            hitPoint("SHOW_HOTLINE")
        }

        // 点击返回
        back.setOnClickListener {
            finish()
        }

        // 点击idcard
        idcardFront.setOnClickListener {
            if (askCameraPermission()) return@setOnClickListener

            fullApplyViewModel.pickPicIndex = 0
            imagePicker.showNow(supportFragmentManager, "0")
            hitPoint("DOC_IDCARD_FRONT_CLICK")
        }
        idcardBack.setOnClickListener {
            if (askCameraPermission()) return@setOnClickListener

            fullApplyViewModel.pickPicIndex = 1
            imagePicker.showNow(supportFragmentManager, "1")
            hitPoint("DOC_IDCARD_BACK_CLICK")
        }

        // 点击face
        startFace.setOnClickListener {
            if (askCameraPermission()) return@setOnClickListener

            val intent = Intent(this@FullApplyGhanaActivity, FaceGhanaDoingActivity::class.java)
            intent.putExtra("imageOutputTag", "2")
            startActivityForResult(intent, REQUEST_CODE_ACTIVITY_FACE_DOING)

            hitPoint("DOC_FACE_CLICK")
        }

        // 点击payroll
        payroll.setOnClickListener {
            if (askCameraPermission()) return@setOnClickListener

            fullApplyViewModel.pickPicIndex = 3
            imagePicker.showNow(supportFragmentManager, "3")
            hitPoint("DOC_PAYROLL_CLICK")
        }

        // 点击water bills
        waterBills.setOnClickListener {
            if (askCameraPermission()) return@setOnClickListener

            fullApplyViewModel.pickPicIndex = 4
            imagePicker.showNow(supportFragmentManager, "4")
            hitPoint("DOC_WATER_BILLS_CLICK")
        }

        // 点击phone bills
        phoneBills.setOnClickListener {
            if (askCameraPermission()) return@setOnClickListener

            fullApplyViewModel.pickPicIndex = 5
            imagePicker.showNow(supportFragmentManager, "5")
            hitPoint("DOC_PHONE_BILLS_CLICK")
        }

        // 拉回显
        fullApplyViewModel.ocrList()
    }

    /**
     * 更新类型选择UI
     */
    private fun selectType(result: FullApplyGhanaTypeResult) {
        if (result.idcardFrontPicBitmap != null) {
            binding.idcardFront.setImageBitmap(result.idcardFrontPicBitmap)
        } else if (result.idcardFrontPicUrl?.isNotBlank() == true) {
            Glide.with(this).load(result.idcardFrontPicUrl).into(binding.idcardFront)
        } else {
            binding.idcardFront.setImageResource(R.drawable.pic_full_apply_idcard_front)
        }

        if (result.idcardBackPicBitmap != null) {
            binding.idcardBack.setImageBitmap(result.idcardBackPicBitmap)
        } else if (result.idcardBackPicUrl?.isNotBlank() == true) {
            Glide.with(this).load(result.idcardBackPicUrl).into(binding.idcardBack)
        } else {
            binding.idcardBack.setImageResource(R.drawable.pic_full_apply_idcard_back)
        }

        if (result.facePicBitmap != null) {
            binding.face.setImageBitmap(result.facePicBitmap)
        } else if (result.facePicUrl?.isNotBlank() == true) {
            Glide.with(this).load(result.facePicUrl).into(binding.face)
        } else {
            binding.face.setImageResource(R.drawable.pic_full_apply_face)
        }

        if (result.payrollPicBitmap != null) {
            binding.payroll.setImageBitmap(result.payrollPicBitmap)
        } else if (result.payrollPicUrl?.isNotBlank() == true) {
            Glide.with(this).load(result.payrollPicUrl).into(binding.payroll)
        } else {
            binding.payroll.setImageResource(R.drawable.pic_full_apply_payroll)
        }

        if (result.waterBillsPicBitmap != null) {
            binding.waterBills.setImageBitmap(result.waterBillsPicBitmap)
        } else if (result.waterBillsPicUrl?.isNotBlank() == true) {
            Glide.with(this).load(result.waterBillsPicUrl).into(binding.waterBills)
        } else {
            binding.waterBills.setImageResource(R.drawable.pic_full_apply_water_bills)
        }

        if (result.phoneBillsPicBitmap != null) {
            binding.phoneBills.setImageBitmap(result.phoneBillsPicBitmap)
        } else if (result.phoneBillsPicUrl?.isNotBlank() == true) {
            Glide.with(this).load(result.phoneBillsPicUrl).into(binding.phoneBills)
        } else {
            binding.phoneBills.setImageResource(R.drawable.pic_full_apply_phone_bills)
        }
    }

    /**
     * 更新类型选择UI
     */
    private fun selectType(
        idcardFrontPicBitmap: Bitmap? = null,
        idcardBackPicBitmap: Bitmap? = null,
        facePicBitmap: Bitmap? = null,
        payrollPicBitmap: Bitmap? = null,
        waterBillsPicBitmap: Bitmap? = null,
        phoneBillsPicBitmap: Bitmap? = null
    ) {
        if (idcardFrontPicBitmap != null) {
            binding.idcardFront.setImageBitmap(idcardFrontPicBitmap)
        } else {
            binding.idcardFront.setImageResource(R.drawable.pic_full_apply_idcard_front)
        }

        if (idcardBackPicBitmap != null) {
            binding.idcardBack.setImageBitmap(idcardBackPicBitmap)
        } else {
            binding.idcardBack.setImageResource(R.drawable.pic_full_apply_idcard_back)
        }

        if (facePicBitmap != null) {
            binding.face.setImageBitmap(facePicBitmap)
        } else {
            binding.face.setImageResource(R.drawable.pic_full_apply_face)
        }

        if (payrollPicBitmap != null) {
            binding.payroll.setImageBitmap(payrollPicBitmap)
        } else {
            binding.payroll.setImageResource(R.drawable.pic_full_apply_payroll)
        }

        if (waterBillsPicBitmap != null) {
            binding.waterBills.setImageBitmap(waterBillsPicBitmap)
        } else {
            binding.waterBills.setImageResource(R.drawable.pic_full_apply_water_bills)
        }

        if (phoneBillsPicBitmap != null) {
            binding.phoneBills.setImageBitmap(phoneBillsPicBitmap)
        } else {
            binding.phoneBills.setImageResource(R.drawable.pic_full_apply_phone_bills)
        }
    }

    /**
     * 请求相机权限
     */
    private fun askCameraPermission(): Boolean {
        val list = mutableListOf(android.Manifest.permission.CAMERA)
        if (checkPermissionsGranted(list)) {
            return false
        }
        // 未同意权限
        EasyPermissions.requestPermissions(
            this,
            "App will request Camera Permission",
            100,
            *(list.toTypedArray())
        )
        return true
    }

    /**
     * 检查权限是否同意
     */
    private fun checkPermissionsGranted(permissionList: List<String>): Boolean {
        val isNotAllGranted = permissionList.any {
            PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, it)
        }
        return !isNotAllGranted
    }

    // ------> EasyPermissions <------
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onRationaleAccepted(requestCode: Int) {
        askCameraPermission()
    }

    override fun onRationaleDenied(requestCode: Int) {
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            SettingsDialog.Builder(this).build().show()
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == DEFAULT_SETTINGS_REQ_CODE) {
            askCameraPermission()
        } else if (requestCode == REQUEST_CODE_ACTIVITY_IDCARD_DOING) {
            if (resultCode == RESULT_OK) {
                val imageOutputPath = data?.getStringExtra("imageOutputPath")
                val imageOutputTag = data?.getStringExtra("imageOutputTag") ?: "0"
                // 更新页面
                fullApplyViewModel.handleTakePictureResult(imageOutputPath, imageOutputTag.toInt())
            }
        } else if (requestCode == REQUEST_CODE_ACTIVITY_PICTURE_DOING) {
            if (resultCode == RESULT_OK) {
                val imageOutputPath = data?.getStringExtra("imageOutputPath")
                val imageOutputTag = data?.getStringExtra("imageOutputTag") ?: "0"
                // 更新页面
                fullApplyViewModel.handleTakePictureResult(imageOutputPath, imageOutputTag.toInt())
            }
        } else if (requestCode == REQUEST_CODE_ACTIVITY_FACE_DOING) {
            if (resultCode == RESULT_OK) {
                val imageOutputPath = data?.getStringExtra("imageOutputPath")
                val imageOutputTag = data?.getStringExtra("imageOutputTag") ?: "0"
                // 更新页面
                fullApplyViewModel.handleTakePictureResult(imageOutputPath, imageOutputTag.toInt())
            }
        }
    }

    fun startNextActivity(
        activity: Class<out AppCompatActivity>? = null,
        params: HashMap<String, String> = HashMap()
    ) {
        val nextActivity = activity ?: return
        try {
            val intent = Intent(this, nextActivity)
//            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
            params.keys.forEach { gKey ->
                intent.putExtra(gKey, params[gKey])
            }
            startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun showMessage(message: String) {
        Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
    }

    override fun onResume() {
        super.onResume()
        hitPoint(type = this::class.java.simpleName, isPageStart = true)
    }

    override fun onPause() {
        super.onPause()
        hitPoint(type = this::class.java.simpleName, isPageEnd = true)
    }
}